<template>
  <el-card style="height: 80px">
    <el-form :inline="true" class="form">
      <el-form-item label="用户名">
        <el-input placeholder="请你输入搜索用户名" v-model="keyword"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          size="default"
          :disabled="keyword ? false : true"
          @click="search"
          >搜索</el-button
        >
        <el-button type="primary" size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <el-card style="margin: 10px 0px">
    <el-button type="primary" size="default" @click="addUser"
      >添加用户</el-button
    >
    <el-button
      type="primary"
      size="default"
      :disabled="selectIdArr.length ? false : true"
      @click="deleteSelectUser"
      >批量删除</el-button
    >
    <!-- table 展示用户信息 -->
    <el-table
      @selection-change="selectChange"
      style="margin: 10px 0px"
      border
      :data="userArr"
    >
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column
        label="用户名字"
        align="center"
        prop="username"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户名称"
        align="center"
        prop="name"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户角色"
        align="center"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="300px" align="center">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="User"
            @click="setRole(row)"
            >分配角色</el-button
          >

          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateUser(row)"
            >编辑</el-button
          >

          <el-popconfirm
            :title="`你确定要删除这个人${row.ROLE}`"
            width="260px"
            @confirm="deleUser(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handler"
      @current-change="getHasUser"
      :current-page="pageNo"
      :page-sizes="[5, 7, 9, 11]"
      v-model:page-size="pageSize"
      layout="prev, pager, next, jumper,->,sizes,total "
      :total="total"
    >
    </el-pagination>
  </el-card>

  <!-- 抽屉结构:完成添加新的用户账号,更新已有的账号信息 -->

  <el-drawer v-model="drawer">
    <!-- 头部标题 -->
    <template #header>
      <h4>{{ userParams.id ? "更新用户" : "添加用户" }}</h4>
    </template>
    <!-- 内容区域 -->
    <template #default>
      <el-form :model="userParams" :rules="rules" ref="formRef">
        <el-form-item label="用户姓名" prop="username">
          <el-input
            placeholder="请您输入用户姓名"
            v-model="userParams.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input
            placeholder="请您输入用户昵称"
            v-model="userParams.name"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="用户密码"
          prop="password"
          v-if="userParams.id == 0"
        >
          <el-input
            placeholder="请您输入用户密码"
            v-model="userParams.password"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 抽屉结构,分配角色 -->

  <el-drawer v-model="drawer1">
    <template #header>
      <h4>分配角色(职位)</h4>
    </template>

    <template #default>
      <el-form>
        <el-form-item label="用户姓名">
          <el-input v-model="userParams.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="职位列表">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <el-checkbox-group
            v-model="userRole"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="(role, index) in allRole"
              :key="role.id"
              :label="role"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>

    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer1 = false">取消</el-button>
        <el-button type="primary" @click="roleSave">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from "vue";
import {
  reqUserInfo,
  reqAllRole,
  reqAddOrUpdateUser,
  reqSetUserRole,
  reqRemoveUser,
  reqSelectUser,
} from "@/api/acl/user";
import type {
  Records,
  User,
  UserResponseData,
  AllRoleResponseData,
  AllRole,
  SetRoleData,
} from "@/api/acl/user/type";
import { ElMessage } from "element-plus";
import userLayOutSettingStore from "@/store/modules/setting";
// 默认页码
let pageNo = ref<number>(1);
// 一页展示几条数据
let pageSize = ref<number>(5);
// 总数据条数
let total = ref<number>(0);
// 存储全部用户的数组
let userArr = ref<Records>([]);
// 定义响应式数据控制抽屉的显示与隐藏
let drawer = ref<boolean>(false);
// 控制分配角色
let drawer1 = ref<boolean>(false);
// 收集用户信息的响应式数据
let userParams = reactive<User>({
  id: 0,
  username: "",
  name: "",
  password: "",
});

// 全选复选框收集数据:是否全选
let checkAll = ref<boolean>(false);
// 设置不确定状态,仅负责于样式控制
const isIndeterminate = ref<boolean>(true);
let allRole = ref<AllRole>([]);
let userRole = ref<AllRole>([]);
// 获取form组件实列
let formRef = ref();

// 准备一个数组存储批量删除的数据ID
let selectIdArr = ref<number[]>([]);
//定义响应式数据:收集用户输入进来的关键字
let keyword = ref<string>("");
// 获取模板setting仓库
let settingStore = userLayOutSettingStore();

// 挂载完毕
onMounted(() => {
  getHasUser();
});

// 获取全部已有的用户信息
const getHasUser = async (pager = 1) => {
  // 收集当前页面
  pageNo.value = pager;
  let result: UserResponseData = await reqUserInfo(
    pageNo.value,
    pageSize.value,
    keyword.value,
  );
  if (result.code == 200) {
    total.value = result.data.total;
    userArr.value = result.data.records;
  }
};

// 分页器下拉菜单自定义事件的回调
const handler = () => {};

// 添加用户按钮的回调
const addUser = () => {
  // 抽屉显示出来
  drawer.value = true;
  // 数据清空
  Object.assign(userParams, {
    id: 0,
    username: "",
    name: "",
    password: "",
  });
  // 清除上一次的错误提示信息
  nextTick(() => {
    formRef.value.resetFields();
  });
};

// 编辑用户按钮
const updateUser = (row: User) => {
  // 抽屉显示出来
  drawer.value = true;

  // 收集已有的账号信息
  Object.assign(userParams, row);

  // 清除上一次的错误提示信息
  nextTick(() => {
    formRef.value.resetFields();
  });
};

// 保存按钮的回调
const save = async () => {
  // 点击保存按钮的时候,务必需要保证表单全部复合去发请求
  await formRef.value.validate();

  // 保存按钮:添加新的用户|更新已有的用户账号信息
  let result: any = await reqAddOrUpdateUser(userParams);

  // 添加或者更新成功
  if (result.code == 200) {
    // 关闭抽屉
    drawer.value = false;
    // 提示消息
    ElMessage({
      type: "success",
      message: userParams.id ? "更新成功" : "添加成功",
    });
    // 获取最新的全部账号的消息
    getHasUser(userParams.id ? pageNo.value : 1);
    // 浏览器自动刷新一次
    window.location.reload();
  } else {
    // 关闭抽屉
    drawer.value = false;
    // 提示信息
    ElMessage({
      type: "error",
      message: userParams.id ? "更新失败" : "添加失败",
    });
  }
};

// 取消按钮的回调
const cancel = () => {
  drawer.value = false;
  // 数据清空
  Object.assign(userParams, {
    username: "",
    name: "",
    password: "",
  });
};

// 校验用户名字回调函数
const validatorUsername = (rule: any, value: any, callBack: any) => {
  // 用户名词 长度必须为五位
  if (value.trim().length >= 5) {
    callBack();
  } else {
    callBack(new Error("Y用户名字至少五位"));
  }
};
// / 校验用户名字回调函数
const validatorName = (rule: any, value: any, callBack: any) => {
  // 用户名词 长度必须为五位
  if (value.trim().length >= 5) {
    callBack();
  } else {
    callBack(new Error("用户昵称至少6位"));
  }
};

// / 校验用户名字回调函数
const validatorPassword = (rule: any, value: any, callBack: any) => {
  // 用户名词 长度必须为五位
  if (value.trim().length >= 6) {
    callBack();
  } else {
    callBack(new Error("用户密码至少五位"));
  }
};

// 表单校验的规则对象
const rules = {
  // 用户名字
  username: [
    { required: true, trigger: "change", validator: validatorUsername },
  ],
  name: [{ required: true, trigger: "blur", validator: validatorName }],
  password: [{ required: true, trigger: "blur", validator: validatorPassword }],
};
// 分配角色按钮的回调
const setRole = async (row: User) => {
  // 储存已有的用户信息
  Object.assign(userParams, row);
  // 获取全部的职位的数据与当前用户已有的职位的数据
  let result: AllRoleResponseData = await reqAllRole(userParams.id as number);
  if (result.code == 200) {
    // 存储全部的职位,
    allRole.value = result.data.allRolesList;
    // 存储当前用户已有的职位
    userRole.value = result.data.assignRoles;
    // 抽屉显示出来
    drawer1.value = true;
  }
};

// 全选复选框的change事件
const handleCheckAllChange = (val: boolean) => {
  userRole.value = val ? allRole.value : [];
  isIndeterminate.value = false;
};

// 底部的复选框change事件
const handleCheckedCitiesChange = (value: string[]) => {
  // 已经勾选的这些项目的长度
  const checkedCount = value.length;
  checkAll.value = checkedCount === allRole.value.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allRole.value.length;
};

// 确定按钮的回调(分配职位)
const roleSave = async () => {
  // 收集参数
  let data: SetRoleData = {
    userId: userParams.id as number,
    roleIdList: userRole.value.map((item) => item.id as number),
  };

  // 分配用户职位
  let result: any = await reqSetUserRole(data);
  if (result.code == 200) {
    // 提示信息
    ElMessage({
      type: "success",
      message: "分配职务成功",
    });
    // 抽屉显示出来
    drawer1.value = false;
    // 获取更新完毕用户的信息
    getHasUser(pageNo.value);
  } else {
    // 提示信息
    ElMessage({
      type: "error",
      message: "分配职位失败",
    });
  }
};

//删除某一用户
const deleUser = async (userId: number) => {
  let result: any = await reqRemoveUser(userId);
  if (result.code == 200) {
    ElMessage({ type: "success", message: "删除成功!" });
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
  }
};

// 勾选事件
const selectChange = (value: any) => {
  selectIdArr.value = value.map((item: any) => {
    return item.id;
  });
};

// 批量删除的事件按钮
const deleteSelectUser = async () => {
  let result: any = await reqSelectUser(selectIdArr.value);

  if (result.code == 200) {
    ElMessage({ type: "success", message: "批量删除成功!" });
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
  } else {
    ElMessage({ type: "error", message: "批量删除失败!" });
  }
};

// 搜索按钮的回调
const search = () => {
  // 根据关键词获取相关的用户数据
  getHasUser();
  // 清空关键字
  keyword.value = "";
};

// 重置按钮的回调
const reset = () => {
  settingStore.refsh = !settingStore.refsh;
};
</script>

<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
